package com.photoeditor.demo.ui.adapter.gallery;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.Toast;

import com.common.base.log.DLog;
import com.common.commercialize.utils.TaskRunnable;
import com.lzy.okgo.OkGo;
import com.photoeditor.R;
import com.photoeditor.demo.app.ActionConstant;
import com.photoeditor.demo.app.AppApplication;
import com.photoeditor.demo.model.bean.BitmapBean;
import com.photoeditor.demo.model.bean.DateBean;
import com.photoeditor.demo.model.bean.SeparatorBean;
import com.photoeditor.demo.model.bean.ThumbnailBean;
import com.photoeditor.demo.model.event.FacePrivacyPolicyEvent;
import com.photoeditor.demo.model.face.FaceConstant;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.activity.GalleryActivity;
import com.photoeditor.demo.ui.activity.community.ConfirmUploadActivity;
import com.photoeditor.demo.ui.activity.edit.EditorImageActivity;
import com.photoeditor.demo.ui.activity.edit.EditorVideoActivity;
import com.photoeditor.demo.ui.activity.edit.ImagePreviewActivity;
import com.photoeditor.demo.ui.activity.face.FaceLogicActivity;
import com.photoeditor.demo.ui.fragement.gallery.FaceGalleryFragment;
import com.photoeditor.demo.ui.widget.gallery.GalleryRowItem;
import com.photoeditor.demo.util.FileUtil;
import com.photoeditor.demo.util.ImageManageUtil;
import com.photoeditor.demo.util.MediaTypeUtil;
import com.photoeditor.demo.util.PermissionUtil;
import com.photoeditor.demo.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Set;

import static com.photoeditor.demo.model.face.FaceConstant.ACTION_FACE_AGING;
import static com.photoeditor.demo.model.face.FaceConstant.ACTION_FUTURE_BABY;
import static com.photoeditor.demo.model.face.FaceConstant.ACTION_GENDER_SWITCH;
import static com.photoeditor.demo.model.face.FaceConstant.ACTION_PAST_LIFE;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FALBUMCHOOSE;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_NFALBUMCHOOSE;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_KEY_FACE_FUN;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_KEY_NFEDITENTER;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_AGING;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_EDIT;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_FILTER;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_GENDER;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_PAST;
import static com.photoeditor.demo.util.DataConstant.IMAGE_DATA;
import static com.photoeditor.demo.util.DataConstant.MAX_DURATION_VIDEO;

/**
 * 用于相册界面展示  照片的ListvIew的Adapter
 * 实现了 SectionIndexer 用于侧边的快速滑动栏
 */
public class ListGridAdapter extends BaseAdapter implements SectionIndexer {
    //数据
    private ArrayList<Object> mList;

    //用于长久存储某个类别有多少个的Map
    private HashMap<String, Integer> mConfirmMap;

    //用于暂时存储某个类别有多少个选中的Map
    private HashMap<String, Integer> mCacheMap;

    //上面的两个Map的key是时间（除了今天的key 是today，其他的都是year-month）， value是数目存储这个的意义是在于快速判别某个类别是否全部选中

    //当前时间  防止包装数据的时间和这边用于计算标签的时间不一致
    private DateBean mNowTime;

    //当前列的数目
    private int mColNum;

    //context
    private GalleryActivity mActivity;

    //用于缓存当前计算出来的图片需要显示的宽度
    private int mImageWidth;

    /**
     * 下面三个都是写死在dimens中的值
     */
    //两张图片间的间距
    private int RIGHT_MARGIN;

    //最后一排的间距
    private int LAST_BOTTOM_MARGIN;

    //显示类别文字的高度
    private int SEPARATOR_HEIGHT;

    //类别（Today  This month  year-month）
    private final int TYPE_SEPARATOR = 1;
    private final int TYPE_IMAGE = 2;

    //用于初始化View
    private LayoutInflater mInfl;

    //当前是不是选中状态
    private boolean isCheckStatus;

    //用于存储选中的列表
    private MyArrayList<ThumbnailBean> mCheckedList;

    //用于存储选中的类别列表
    private ArrayList<SeparatorBean> mSeparatorList;

    //用于回调
    private ICheckedChangeListener mListener;

    //用于存储选中的视频数量
    private int mCheckedVideoNum;

    //用于标识有没有选中video
    private boolean mHasCheckedVideo;
    private LinkedHashMap<String, Integer> mIndexMap;
    private String[] mIndexkey;
    private int mPhotoLength;
    private String mFrom;

    public ListGridAdapter(ArrayList<Object> uris, LinkedHashMap<String, Integer> map, int colNum, GalleryActivity context, long nowTime) {
        isCheckStatus = false;
        mHasCheckedVideo = false;
        mCheckedVideoNum = 0;
        Resources res = context.getResources();
        SEPARATOR_HEIGHT = res.getDimensionPixelSize(R.dimen.gallery_separator_height);
        RIGHT_MARGIN = res.getDimensionPixelSize(R.dimen.gallery_distance);
        LAST_BOTTOM_MARGIN = res.getDimensionPixelSize(R.dimen.gallery_last_bottom_height);
        mCheckedList = new MyArrayList<ThumbnailBean>();
        mSeparatorList = new ArrayList<SeparatorBean>();
        mCacheMap = new HashMap<String, Integer>();
        mList = uris;
        mConfirmMap = map;
        mNowTime = new DateBean(nowTime);
        initCacheMap(true);
//		for(String key: map.keySet()){
//			System.out.println("key = " + key + "  value = " + map.get(key));
//		}
        mColNum = colNum;
        mActivity = context;
        this.mInfl = ((Activity) context).getLayoutInflater();
        mImageWidth = (ImageManageUtil.getScreenWidth() - (colNum - 1) * RIGHT_MARGIN) / mColNum;
        countIndexer(map);
    }

    public void setFromWhere(String fromWhere) {
        mFrom = fromWhere;
    }

    @Override
    public int getCount() {
        if (mList != null) {
            return mList.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (mList != null) {
            return mList.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Object o = getItem(position);
        if (o != null) {
            ViewHolder mHolder = null;
            GalleryRowItem gview;
            if (convertView == null) {
                convertView = new LinearLayout(mActivity);
                gview = new GalleryRowItem(mActivity, mColNum);
                gview.setListener(new GalleryRowItem.OperationListener() {

                    @Override
                    public void OnLongClick(GalleryRowItem item, ThumbnailBean bean, int position) {
                        if (mActivity.isPickMode()) {
                            mActivity.showImageView(null, item, bean, item.getThumbRect(bean), item.getThumbBitmap(bean));
                        } else {
                            if (!isCheckStatus) {
                                boolean ischecked = bean.isChecked();
                                if (MediaTypeUtil.isVideo(bean.getType())) {
                                    bean.setChecked(!ischecked);
                                    setCheckStatus(!isCheckStatus);
                                    confirmSeparatorStatus(bean, position);
                                    if (bean.isChecked()) {
                                        setCheckedVideo(true);
                                        mCheckedList.add(bean);
                                    } else {
                                        setCheckedVideo(false);
                                        mCheckedList.remove(bean);
                                    }
                                } else {
                                    bean.setChecked(!ischecked);
                                    setCheckStatus(!isCheckStatus);
                                    confirmSeparatorStatus(bean, position);
                                    if (bean.isChecked()) {
                                        mCheckedList.add(bean);
                                    } else {
                                        mCheckedList.remove(bean);
                                    }
                                }
                                item.updateItemStatus();
                                if (SPDataManager.isShowSelectMultiPreviewTip()) {
                                }
                            } else {
                                mActivity.showImageView(null, item, bean, item.getThumbRect(bean), item.getThumbBitmap(bean));
                            }
                        }
                    }

                    @Override
                    public void OnClick(final GalleryRowItem item, final ThumbnailBean bean, int position) {
                        if (bean.getPath().equals("open_camera")) {//camera icon
                            takePhoto();
                            return;
                        }
                        DLog.d("wLog", "Gallery item click mFrom: " + mFrom);
                        if (FaceGalleryFragment.fromFaceFragment) {
                            if (!FaceGalleryFragment.takePhotoFinish) {
                                return;
                            }
                            if (bean.getPath().equals("loading")) {//loading
                                return;
                            }
                            if (SpUtils.obtain().getBoolean("first_edit", true)) {
                                if (!bean.getPath().equals("model1") && !bean.getPath().equals("model2")) {
                                    showPrivateDialog(item, bean, position);
                                    return;
                                }
                            }
                            if (!TextUtils.isEmpty(mFrom) && mFrom.contains("main_page_")) {
                                switch (mFrom) {
                                    case "main_page_aging":
                                        StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_FALBUMCHOOSE, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_AGING);
                                        break;
                                    case "main_page_gender_swap":
                                        StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_FALBUMCHOOSE, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_GENDER);
                                        break;
                                    case "main_page_past_life":
                                        StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_FALBUMCHOOSE, STATISTIC_KEY_FACE_FUN, STATISTIC_VALUE_PAST);
                                        break;
                                }
                            }
                            gotoFaceReportActivity(bean, false);
                            return;
                        }
                        if (!TextUtils.isEmpty(mFrom)) {
                            switch (mFrom) {
                                case "main_page_editor_filter":
                                    StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_NFALBUMCHOOSE, STATISTIC_KEY_NFEDITENTER, STATISTIC_VALUE_FILTER);
                                    break;
                                case "main_page_editor_floating":
                                    StatisticsUtils.statisticGrowingIo(STATISTIC_EVENT_NFALBUMCHOOSE, STATISTIC_KEY_NFEDITENTER, STATISTIC_VALUE_EDIT);
                                    break;
                            }
                        }
                        gotoImageEditActivity(item, bean, position);
                    }

                    @Override
                    public void OnCheckBoxClick(GalleryRowItem item, SeparatorBean bean, int position) {
                        if (mActivity.isPickMode()) {
                            //do nonthing
                        } else {
                            if (isCheckStatus) {
                                boolean ischecked = !bean.isChecked();
                                bean.setChecked(ischecked);
                                if (ischecked) {
                                    checkCategory(position, bean);
                                    mSeparatorList.add(bean);
                                } else {
                                    unCheckCategory(position, bean);
                                    mSeparatorList.remove(bean);
                                }
                                item.updateItemStatus();
                            }
                        }
                    }

                    @Override
                    public void OnPlayVideoClick(GalleryRowItem item, final ThumbnailBean bean, int position) {
                        if (mActivity.isPickMode()) {
                            if (mActivity.isPickToEditModeAndShare()) {
                                if (MediaTypeUtil.isImage(bean.getType())) {
                                    EditorImageActivity.startImageEditActivityAndShare(mActivity, bean.getUri(), bean.getDegree(), false);
                                    mActivity.setNeedExitPageAd(false);
                                    mActivity.finish();
                                } else {//video
                                    ImagePreviewActivity.startGallerySelectMotionViewAndShare(mActivity, bean.getUri());
                                    mActivity.setNeedExitPageAd(false);
                                    mActivity.finish();
                                }
                            } else if (mActivity.isPickToCollageMode() || mActivity.isPickToCollageMode4Template()) {
                                if (mActivity.canSelect(bean.getType())) {
                                    bean.setSelectCount(bean.getSelectCount() + 1);
                                    item.updateItemStatus();
                                }
//								mActivity.addCollageBitmap(bean, false, mType, item.getThumbBitmap(bean));
                            } else if (mActivity.isPickScreenLockBg()) {
                                if (mActivity.canSelect(bean.getType())) {
                                    bean.setSelectCount(bean.getSelectCount() + 1);
                                    item.updateItemStatus();
                                }
//								mActivity.addCollageBitmap(bean, true, mType, item.getThumbBitmap(bean));
                            } else if (mActivity.isChangeToCollageMode()) {
                                Intent data = mActivity.getIntent();
                                BitmapBean bitmapBean = new BitmapBean();
                                bitmapBean.mUri = bean.getUri();
                                bitmapBean.mType = bean.getType();
                                bitmapBean.mPath = bean.getPath();
                                bitmapBean.mDegree = bean.getDegree();
                                Bundle bundle = new Bundle();
                                bundle.putParcelable(IMAGE_DATA, bitmapBean);
                                data.putExtra(IMAGE_DATA, bundle);
                                mActivity.setNeedExitPageAd(false);
                                mActivity.setResult(Activity.RESULT_OK, data);
                                mActivity.finish();
                            } else if (mActivity.isChangeToFreestyleMode()) {
                                Intent data = mActivity.getIntent();
                                BitmapBean bitmapBean = new BitmapBean();
                                bitmapBean.mUri = bean.getUri();
                                bitmapBean.mType = bean.getType();
                                bitmapBean.mPath = bean.getPath();
                                bitmapBean.mDegree = bean.getDegree();
                                Bundle bundle = new Bundle();
                                bundle.putParcelable(IMAGE_DATA, bitmapBean);
                                data.putExtra(IMAGE_DATA, bundle);
                                mActivity.setNeedExitPageAd(false);
                                mActivity.setResult(Activity.RESULT_OK, data);
                                mActivity.finish();
                            } else if (mActivity.isPickToEditMode()) {
                                if (MediaTypeUtil.isImage(bean.getType())) {
                                    EditorImageActivity.startImageEditActivity(mActivity, bean.getUri(), bean.getDegree(), ActionConstant.Actions.ACTION_PICK_TO_EDIT
                                            , GalleryActivity.REQUEST_CODE_PICK_TO_EDIT, mActivity.getMainButtonEntrance(), mFrom);
                                } else {
                                    if (bean.getDuration() > MAX_DURATION_VIDEO && SPDataManager.needShowByond30sVideoTip()) {
                                        // 选中超过30s视频，第一次弹窗提示：超过30s视频在collage时会被裁剪成30s
                                        SPDataManager.setShowByond30sVideoTip(false);
                                        GalleryActivity.showSelBeyond30sVideoDialog(item.getContext(), new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                EditorVideoActivity.startVideoEditActivity(mActivity, bean.getPath(), ActionConstant.Actions.ACTION_PICK_TO_EDIT
                                                        , GalleryActivity.REQUEST_CODE_PICK_TO_EDIT);
                                            }
                                        });
                                    } else {
                                        EditorVideoActivity.startVideoEditActivity(mActivity, bean.getPath(), ActionConstant.Actions.ACTION_PICK_TO_EDIT
                                                , GalleryActivity.REQUEST_CODE_PICK_TO_EDIT);
                                    }
                                }
                            } else if (mActivity.isPickToEditAndPublishMode()) {
                                if (MediaTypeUtil.isImage(bean.getType())) {
                                    EditorImageActivity.startImageEditActivityAndPublish(mActivity, bean.getUri(), bean.getDegree(),
                                            false, mActivity.getTopicIdFromIntent());
                                    mActivity.setNeedExitPageAd(false);
                                    mActivity.finish();
                                } else {
                                    EditorVideoActivity.startVideoEditActivity(mActivity, bean.getPath(), GalleryActivity.REQUEST_CODE_PICK_TO_EDIT, mActivity.getTopicIdFromIntent());
                                    mActivity.setNeedExitPageAd(false);
                                    mActivity.finish();
                                }
                            } else {
                                Intent data = mActivity.getIntent();
                                data.setData(bean.getUri());
                                mActivity.setNeedExitPageAd(false);
                                mActivity.setResult(Activity.RESULT_OK, data);
                                mActivity.finish();
                            }
                        } else {
                            if (!isCheckStatus) {
                                try {
                                    Intent intent = new Intent(Intent.ACTION_VIEW);
                                    intent.setDataAndType(bean.getUri(), "video/*");
                                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                                    mActivity.startActivity(intent);
                                } catch (Throwable e) {
                                    Toast.makeText(mActivity, R.string.no_suitable_player, Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                bean.setChecked(!bean.isChecked());
                                confirmSeparatorStatus(bean, position);
                                if (bean.isChecked()) {
                                    mCheckedList.add(bean);
                                } else {
                                    mCheckedList.remove(bean);
                                }
                                item.updateItemStatus();
                            }
                        }
                    }

                    @Override
                    public void OnDown(GalleryRowItem item) {
                    }

                    @Override
                    public void OnUp(GalleryRowItem item) {
                        mActivity.hideImageView(item);
                    }
                });
                ((LinearLayout) convertView).addView(gview);
                mHolder = new ViewHolder();
                mHolder.item = gview;
                convertView.setTag(mHolder);
            } else {
                mHolder = (ViewHolder) convertView.getTag();
                gview = mHolder.item;
                gview.removeAllViews();
            }

            Object next = null;
            if (position == getCount() - 1) {
                convertView.setPadding(0, 0, 0, LAST_BOTTOM_MARGIN);
            } else {
                convertView.setPadding(0, 0, 0, 0);
                next = getItem(position + 1);
            }

            if (o instanceof ArrayList) {
                ArrayList<Object> data = (ArrayList<Object>) o;
                gview.setTypeAndData(GalleryRowItem.TYPE_IMAGE, data, isCheckStatus, position, mActivity.isPickToCollageMode() || mActivity.isPickToCollageMode4Template() || mActivity.isPickToFreeStyle() || mActivity.isAddImage4Freestyle());
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, gview.getItemHeight());
                if (next != null && next instanceof ArrayList) {
                    lp.bottomMargin = RIGHT_MARGIN;
                }
                gview.setLayoutParams(lp);
            } else if (o instanceof SeparatorBean) {
                SeparatorBean data = (SeparatorBean) o;
                gview.setTypeAndData(GalleryRowItem.TYPE_SEPARATOR, data, isCheckStatus, position);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, gview.getItemHeight());
                gview.setLayoutParams(lp);
            }
            return convertView;
        }
        return null;
    }

    public void gotoFaceReportActivity(ThumbnailBean bean, boolean fromCameraBack) {
        if (!TextUtils.isEmpty(mFrom) && mFrom.contains("main_page")) {
            //从主页打开，进入结果页
            String path;
            String action;
            int from;
            if (bean.getPath().equals("model1") || bean.getPath().equals("model2")) {
                path = "model/model_female.png";
                from = 0;
            } else {
                path = bean.getPath();
                from = 1;
            }
            if (fromCameraBack) {
                from = 2;
            }
            if (TextUtils.equals(mFrom, "main_page_gender_swap")) {
                action = ACTION_GENDER_SWITCH;
            } else if (TextUtils.equals(mFrom, "main_page_past_life")) {
                action = ACTION_PAST_LIFE;
            } else if (TextUtils.equals(mFrom, "main_page_aging")) {
                action = ACTION_FACE_AGING;
            } else if (TextUtils.equals(mFrom, "main_page_baby_predict")) {
                action = ACTION_FUTURE_BABY;
            } else {
                action = "";
            }
            FaceLogicActivity.showReportActivity(mActivity, action, from, path);
            mActivity.finish();
        } else {
            Intent intent = new Intent();
            if (bean.getPath().equals("model1") || bean.getPath().equals("model2")) {
    //			intent.setData(null);
                intent.putExtra("EXTRA_KEY_IMAGE_YOUS", "model/model_female.png");
                intent.putExtra(FaceConstant.EXTRA_FROM, 0);
            } else {
                intent.setData(bean.getUri());
                if (bean.isChecked()) {
                    intent.putExtra(FaceConstant.EXTRA_FROM, 2);
                } else {
                    intent.putExtra(FaceConstant.EXTRA_FROM, 1);
                }
            }
            if (fromCameraBack) {
                intent.putExtra(FaceConstant.EXTRA_FROM, 2);
            }

    //		intent.putExtra("degree", bean.getDegree());
            FaceLogicActivity.degree = bean.getDegree();
            mActivity.setResult(Activity.RESULT_OK, intent);
            mActivity.finish();
        }
    }

    /**
     * 这个方法有10个以上的if case，没有注释，我找了我要的case，标注了下，就这样了
     */
    public void gotoImageEditActivity(final GalleryRowItem item, final ThumbnailBean bean, int position) {
        if (mActivity.isPickMode()) {
            if (mActivity.isPickToEditModeAndShare()) {
                if (MediaTypeUtil.isImage(bean.getType())) {
                    EditorImageActivity.startImageEditActivityAndShare(mActivity, bean.getUri(),
                            bean.getDegree(), false);
                    mActivity.setNeedExitPageAd(false);
                    mActivity.finish();
                } else {
                    ImagePreviewActivity.startGallerySelectMotionViewAndShare(mActivity, bean.getUri());
                    mActivity.setNeedExitPageAd(false);
                    mActivity.finish();
                }
            } else if (mActivity.isPickToCollageMode() || mActivity.isPickToCollageMode4Template() || mActivity.isPickToFreeStyle() || mActivity.isAddImage4Freestyle()) {
                if (mActivity.canSelect(bean.getType())) {
                    bean.setSelectCount(bean.getSelectCount() + 1);
                    item.updateItemStatus();
                }
//								mActivity.addCollageBitmap(bean, false, mType, item.getThumbBitmap(bean));
            } else if (mActivity.isPickScreenLockBg()) {
                if (mActivity.canSelect(bean.getType())) {
                    bean.setSelectCount(bean.getSelectCount() + 1);
                    item.updateItemStatus();
                }
//								mActivity.addCollageBitmap(bean, true, mType, item.getThumbBitmap(bean));
            } else if (mActivity.isChangeToCollageMode()) {
                Intent data = mActivity.getIntent();
                BitmapBean bitmapBean = new BitmapBean();
                bitmapBean.mUri = bean.getUri();
                bitmapBean.mType = bean.getType();
                bitmapBean.mPath = bean.getPath();
                bitmapBean.mDegree = bean.getDegree();
                Bundle bundle = new Bundle();
                bundle.putParcelable(IMAGE_DATA, bitmapBean);
                data.putExtra(IMAGE_DATA, bundle);
                mActivity.setNeedExitPageAd(false);
                mActivity.setResult(Activity.RESULT_OK, data);
                mActivity.finish();
            } else if (mActivity.isChangeToFreestyleMode()) {
                Intent data = mActivity.getIntent();
                BitmapBean bitmapBean = new BitmapBean();
                bitmapBean.mUri = bean.getUri();
                bitmapBean.mType = bean.getType();
                bitmapBean.mPath = bean.getPath();
                bitmapBean.mDegree = bean.getDegree();
                Bundle bundle = new Bundle();
                bundle.putParcelable(IMAGE_DATA, bitmapBean);
                data.putExtra(IMAGE_DATA, bundle);
                mActivity.setNeedExitPageAd(false);
                mActivity.setResult(Activity.RESULT_OK, data);
                mActivity.finish();
            } else if (mActivity.isPickToEditMode()) {
                TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
                    @Override
                    public void run() {
                        if (MediaTypeUtil.isImage(bean.getType())) {
                            //进入艺术滤镜
                            if (mActivity.isEnterArtistFilter()) {
                                EditorImageActivity.startImageEditActivityForArtist(mActivity, bean.getUri(), bean.getDegree(), ActionConstant.Actions.ACTION_PICK_TO_EDIT
                                        , GalleryActivity.REQUEST_CODE_PICK_TO_EDIT, mActivity.getMainButtonEntrance());
                            } else {
                                EditorImageActivity.startImageEditActivity(mActivity, bean.getUri(), bean.getDegree(), ActionConstant.Actions.ACTION_PICK_TO_EDIT
                                        , GalleryActivity.REQUEST_CODE_PICK_TO_EDIT, mActivity.getMainButtonEntrance(), mFrom);
                            }
                            mActivity.statisticsMainBtnAlbumStart();
                        } else {
                            if (bean.getDuration() > MAX_DURATION_VIDEO && SPDataManager.needShowByond30sVideoTip()) {
                                // 选中超过30s视频，第一次弹窗提示：超过30s视频在collage时会被裁剪成30s
                                SPDataManager.setShowByond30sVideoTip(false);
                                GalleryActivity.showSelBeyond30sVideoDialog(item.getContext(), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        EditorVideoActivity.startVideoEditActivity(mActivity, bean.getPath(), ActionConstant.Actions.ACTION_PICK_TO_EDIT
                                                , GalleryActivity.REQUEST_CODE_PICK_TO_EDIT, mActivity.getMainButtonEntrance());
                                    }
                                });
                                mActivity.statisticsMainBtnAlbumStart();
                            } else {
                                EditorVideoActivity.startVideoEditActivity(mActivity, bean.getPath(), ActionConstant.Actions.ACTION_PICK_TO_EDIT
                                        , GalleryActivity.REQUEST_CODE_PICK_TO_EDIT, mActivity.getMainButtonEntrance());
                                mActivity.statisticsMainBtnAlbumStart();
                            }
                        }
                    }
                };
                mActivity.showAd(taskRunnable);
            } else if (mActivity.isPickToEditAndPublishMode()) {
                if (MediaTypeUtil.isGif(bean.getType())) {
                    ConfirmUploadActivity.startConfirmUploadActivity(mActivity, bean.getPath(), mActivity.getTopicIdFromIntent());
                    mActivity.setNeedExitPageAd(false);
                    mActivity.finish();
                } else if (MediaTypeUtil.isImage(bean.getType())) {
                    EditorImageActivity.startImageEditActivityAndPublish(mActivity, bean.getUri(), bean.getDegree(),
                            false, mActivity.getTopicIdFromIntent());
                    mActivity.setNeedExitPageAd(false);
                    mActivity.finish();
                } else {
                    EditorVideoActivity.startVideoEditActivity(mActivity, bean.getPath(),
                            GalleryActivity.REQUEST_CODE_PICK_TO_EDIT, mActivity.getTopicIdFromIntent());
                    mActivity.setNeedExitPageAd(false);
                    mActivity.finish();
                }
			} else if (mActivity.isPickToAddSticker()) {
				TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
					@Override
					public void run() {
						EditorImageActivity.startImageEditActivityGoToAddEmoji(mActivity, bean.getUri(), bean.getDegree(),
								false, mActivity.getStickerPkgName(), mActivity.getGifTitle(), mActivity.getAutoScrollPosition());
						mActivity.setNeedExitPageAd(false);
						mActivity.finish();
					}
				};
				mActivity.showAd(taskRunnable);
            } else if (mActivity.isPickToApplyFilter()) {
                TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
                    @Override
                    public void run() {
                        EditorImageActivity.startImageEditActivityToApplyFilter(mActivity, bean.getUri(), mActivity.getFilerCategoryId(),
                                mActivity.getFilterPkgName(), bean.getDegree(), mFrom);
                        mActivity.setNeedExitPageAd(false);
                        mActivity.finish();
                    }
                };
                mActivity.showAd(taskRunnable);
            } else if (mActivity.isPickToBeautyEditMode()) {
                TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
                    @Override
                    public void run() {
                        EditorImageActivity.startImageEditActivityGoToBeauty(mActivity, bean.getUri(), bean.getDegree(), mActivity.getMainButtonEntrance());
                        mActivity.setNeedExitPageAd(false);
                        mActivity.statisticsMainBtnAlbumStart();
                        mActivity.finish();
                    }
                };
                mActivity.showAd(taskRunnable);
            } else if (mActivity.isPickToBeautyFuntionEditMode()) {
                TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
                    @Override
                    public void run() {
                        String type = mActivity.getIntent().getStringExtra(ActionConstant.Extras.EXTRA_BEAUTY_FUNTION_TYPE);
                        if (TextUtils.isEmpty(type)) {
                            return;
                        }
                        EditorImageActivity.startImageEditActivityGoToBeautyOrBodyFuntion(mActivity,
                                bean.getUri(), bean.getDegree(), type, mActivity.getMainButtonEntrance());
                        mActivity.setNeedExitPageAd(false);
                        mActivity.statisticsMainBtnAlbumStart();
                        mActivity.finish();
                    }
                };
                mActivity.showAd(taskRunnable);
            } else {
                Intent data = mActivity.getIntent();
                data.setData(bean.getUri());
                mActivity.setResult(Activity.RESULT_OK, data);
                mActivity.setNeedExitPageAd(false);
                mActivity.finish();
            }
        } else {
            if (isCheckStatus) {
                if (MediaTypeUtil.isVideo(bean.getType())) {
                    bean.setChecked(!bean.isChecked());
                    confirmSeparatorStatus(bean, position);
                    if (bean.isChecked()) {
                        setCheckedVideo(true);
                        mCheckedList.add(bean);
                    } else {
                        setCheckedVideo(false);
                        mCheckedList.remove(bean);
                    }
                } else {
                    bean.setChecked(!bean.isChecked());
                    confirmSeparatorStatus(bean, position);
                    if (bean.isChecked()) {
                        mCheckedList.add(bean);
                    } else {
                        mCheckedList.remove(bean);
                    }
                }
                item.updateItemStatus();
            } else {
                if (mActivity instanceof GalleryActivity) {
                    TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
                        @Override
                        public void run() {
                            GalleryActivity activity = (GalleryActivity) mActivity;
                            activity.startImagePreviewActivity(bean);
                        }
                    };
                    mActivity.showAd(taskRunnable);
                }
            }
        }
    }

//	private boolean fromFacePage = false;
//	public void setFromFace(boolean b){
//		fromFacePage = b;
//	}

    public void showPrivateDialog(final GalleryRowItem item, final ThumbnailBean bean, final int position) {
//        TextView tvLink = new TextView(mActivity);
//        tvLink.setText("Privacy Policy");
//        tvLink.setTextColor(Color.parseColor("#1b1b1b"));
//        tvLink.setPadding(72, 32, 0, 0);
//        tvLink.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
//        tvLink.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //todo goto隐私协议
//                AndroidDevice.startWebView(mActivity, Global.PRIVACY_URL);
//            }
//        });
//
//        AlertDialog dialog = new AlertDialog.Builder(mActivity)
//                .setTitle("Tips")
//                .setMessage("We need to upload the photos you select to analyze and face transform. They will be automatically deleted after the analysis.")
//                .setView(tvLink)
//                .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                })
//                .setPositiveButton("AGREE", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        SpUtils.obtain().save("first_edit", false);
//                        //
//                        gotoFaceReportActivity(bean);
//                    }
//                })
//                .show();
//        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLUE);
//        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.GRAY);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoFaceReportActivity(bean, false);
            }
        };
        EventBus.getDefault().post(new FacePrivacyPolicyEvent(onClickListener));
    }

    private void takePhoto() {
//        if(ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
//            mActivity.startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), GalleryActivity.REQUEST_CODE_TAKEPHOTO);
//        }else{
//            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.CAMERA}, 0x1000);
//        }
        if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            SpUtils.obtain().save(mActivity.SP_REJECT_CAMERA_PERMISSION, false);
            //用于保存调用相机拍照后所生成的文件
//			if(! new File(Environment.getExternalStorageDirectory().getPath(), "/DCIM/PhotoEditor/").exists()){
//				new File(Environment.getExternalStorageDirectory().getPath(), "/DCIM/PhotoEditor/").mkdir();
//			}
            if (FaceGalleryFragment.fromFaceFragment && !FaceGalleryFragment.takePhotoFinish) {
                return;
            }
            String path = mActivity.getExternalCacheDir().getPath() + "/" + System.currentTimeMillis() + ".jpg";
            SpUtils.obtain().save("camera_image_path", path);
            Uri uri;
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileUtil.getExternalFileUri(path);
                intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            } else {
                uri = Uri.fromFile(new File(path));
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            mActivity.startActivityForResult(intent, GalleryActivity.REQUEST_CODE_TAKEPHOTO);
            if (FaceGalleryFragment.fromFaceFragment)
                FaceGalleryFragment.takePhotoFinish = false;
        } else {
            if (SpUtils.obtain().getBoolean(mActivity.SP_REJECT_CAMERA_PERMISSION, false)){
                ToastUtil.showToast(R.string.permission_camera_tips);
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", AppApplication.getApplication().getPackageName(), null);
                intent.setData(uri);
                mActivity.startActivity(intent);
            }else {
                ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}, mActivity.PERMISSION_CAMERA_CODE);
            }
        }
    }

    /**
     * 获取接口请求的耗时区间
     *
     * @param startRequest 开始请求时间
     * @return 区间文本
     */
    private String getTimeInterval(long startRequest) {
        long successRequest = System.currentTimeMillis();
        long diff = successRequest - startRequest;
        float second = diff / 1000f;
        String secondText = "";
        if (second < 4) {
            secondText = "[0.4)";
        } else if (second >= 4 && second < 6) {
            secondText = "[4.6)";
        } else if (second >= 6 && second < 10) {
            secondText = "[6.10)";
        } else if (second >= 10) {
            secondText = "[10.)";
        }
        return secondText;
    }

    @Override
    public int getItemViewType(int position) {
        Object object = getItem(position);
        if (object != null) {
            if (object instanceof ArrayList) {
                return TYPE_IMAGE;
            } else if (object instanceof SeparatorBean) {
                return TYPE_SEPARATOR;
            }
        }
        return super.getItemViewType(position);
    }

    @Override
    public boolean isEnabled(int position) {
        if (getItemViewType(position) == TYPE_SEPARATOR && !isCheckStatus) {
            return false;
        } else {
            return super.isEnabled(position);
        }
    }

    public boolean isCheckStatus() {
        return isCheckStatus;
    }

    /**
     * 设置当前是选中状态还是非选中状态
     *
     * @param isCheckStatus
     */
    public void setCheckStatus(boolean isCheckStatus) {
        if (isCheckStatus != this.isCheckStatus) {
            this.isCheckStatus = isCheckStatus;
            if (!isCheckStatus) {
                resetCheckedVideo();
                restoreCheckedList();
                restoreSeparatorList();
                initCacheMap(true);
            }
            if (mListener != null) {
                mListener.onCheckedStatusChange(isCheckStatus);
            }
            notifyDataSetChanged();
        }
    }

    public void setOnCheckedChangeListener(ICheckedChangeListener l) {
        mListener = l;
    }

    /**
     * 获取当前选中的list  深度复制
     *
     * @return
     */
    public ArrayList<ThumbnailBean> getCheckedList() {
        ArrayList<ThumbnailBean> result = new ArrayList<ThumbnailBean>();
        int l = mCheckedList.size();
        for (int i = 0; i < l; i++) {
            result.add(mCheckedList.get(i));
        }
        return result;
    }

    /**
     * 取消选择时调用 先设置为unchecked然后clear
     */
    public void restoreCheckedList() {
        int l = mCheckedList.size();
        for (int i = 0; i < l; i++) {
            mCheckedList.get(i).setChecked(false);
        }
        mCheckedList.clear();
    }

    /**
     * 取消选择Separator时调用 先设置为unchecked然后clear
     */
    public void restoreSeparatorList() {
        int l = mSeparatorList.size();
        for (int i = 0; i < l; i++) {
            mSeparatorList.get(i).setChecked(false);
        }
        mSeparatorList.clear();
    }

    /**
     * 删除时调用 只是clear了
     */
    public void clearCheckedList() {
        mCheckedList.clear();
    }

    /**
     * 删除时调用 只是clear了
     */
    public void clearSeparatorList() {
        mSeparatorList.clear();
    }

    /**
     * nowTime用于记录今天的时间
     *
     * @param datas
     * @param map
     * @param nowTime
     */
    public void setData(ArrayList<Object> datas, LinkedHashMap<String, Integer> map, long nowTime) {
        if (mList != null && mList.size() != 0) {
            mList.clear();
        }
        if (mConfirmMap != null) {
            mConfirmMap.clear();
        }
        mList = datas;
        mConfirmMap = map;
        mNowTime = new DateBean(nowTime);
        initCacheMap(true);
        countIndexer(map);
//		for(String key: map.keySet()){
//			System.out.println("key = " + key + "  value = " + map.get(key));
//		}
        notifyDataSetChanged();
    }

    /**
     * 选择一个类别
     *
     * @param position
     */
    public void checkCategory(int position, SeparatorBean sbean) {
        int i = position + 1;
        int len = mList.size();
        Object o = mList.get(i);
        while (o != null && o instanceof ArrayList) {
            ArrayList<Object> data = (ArrayList<Object>) o;
            int num = data.size();
            for (int j = 0; j < num; j++) {
                Object item = data.get(j);
                if (item instanceof ThumbnailBean) {
                    ThumbnailBean bean = (ThumbnailBean) item;
                    if (!bean.isChecked()) {
                        bean.setChecked(true);
                        if (MediaTypeUtil.isVideo(bean.getType())) {
                            setCheckedVideo(true);
                        }
                        mCheckedList.add(bean);
                    }
                }
            }
            if (i == len - 1) {
                break;
            }
            i++;
            o = mList.get(i);
        }
        countCacheMapValue(sbean, true);
        notifyDataSetChanged();
    }

    /**
     * 取消选择一个类别
     *
     * @param position
     */
    public void unCheckCategory(int position, SeparatorBean sbean) {
        int i = position + 1;
        int len = mList.size();
        Object o = mList.get(i);
        while (o != null && o instanceof ArrayList) {
            ArrayList<Object> data = (ArrayList<Object>) o;
            int num = data.size();
            for (int j = 0; j < num; j++) {
                Object item = data.get(j);
                if (item instanceof ThumbnailBean) {
                    ThumbnailBean bean = (ThumbnailBean) item;
                    if (bean.isChecked()) {
                        bean.setChecked(false);
                        if (MediaTypeUtil.isVideo(bean.getType())) {
                            setCheckedVideo(false);
                        }
                        mCheckedList.remove(bean);
                    }
                }
            }
            if (i == len - 1) {
                break;
            }
            i++;
            o = mList.get(i);
        }
        countCacheMapValue(sbean, false);
        notifyDataSetChanged();
    }

    Object okObject = this;

    public void cancelCall() {
        DLog.d("wmgTest", "cancelCall");
        OkGo.getInstance().cancelTag(okObject);
    }

    /**
     * 全选或者全不选
     *
     * @param checked
     */
    public void checkAll(boolean checked) {
        if (mList == null) return;
        if (checked) {
            initCacheMap(false);
            int len = mList.size();
            clearSeparatorList();
            initCheckedVideo();
            for (int i = 0; i < len; i++) {
                Object o = mList.get(i);
                if (o instanceof ArrayList) {
                    ArrayList<Object> data = (ArrayList<Object>) o;
                    int l = data.size();
                    for (int j = 0; j < l; j++) {
                        Object item = data.get(j);
                        if (item instanceof ThumbnailBean) {
                            ThumbnailBean bean = (ThumbnailBean) item;
                            if (!bean.isChecked()) {
                                bean.setChecked(true);
                                if (MediaTypeUtil.isVideo(bean.getType())) {
                                    setCheckedVideo(true);
                                }
                                mCheckedList.add(bean);
                            }
                        }
                    }
                } else if (o instanceof SeparatorBean) {
                    SeparatorBean bean = (SeparatorBean) o;
                    bean.setChecked(true);
                    mSeparatorList.add(bean);
                }
            }
        } else {
            resetCheckedVideo();
            restoreCheckedList();
            restoreSeparatorList();
            initCacheMap(true);
        }
        notifyDataSetChanged();
    }

    /**
     * 用于检查当前是否有一个类别被全选中 或 未被全选中
     */
    private void confirmSeparatorStatus(ThumbnailBean bean, int position) {
        if (mConfirmMap == null || mCacheMap == null) {
            return;
        }
        DateBean beanDate = new DateBean(bean.getDate());
        String key;
        if (beanDate.isSameDay(mNowTime)) {
            key = GalleryActivity.TODAY_KEY;
        } else if (mConfirmMap.get(GalleryActivity.TODAY_KEY) != null && beanDate.isYesterday(mNowTime)) {//存在今天的时候才会有昨天
            key = GalleryActivity.YESTERDAY_KEY;
        } else if (beanDate.isDurationDays(mNowTime, 7)) {
            key = beanDate.getMonthDayString();
        } else if (beanDate.isSameMonth(mNowTime)) {
            key = GalleryActivity.MONTH_KEY;
        } else {
            key = beanDate.getYearMonthString();
        }
        int aValue = mConfirmMap.get(key);
        int cValue = mCacheMap.get(key);

        if (bean.isChecked()) {
            mCacheMap.put(key, ++cValue);
        } else if (cValue > 0) {
            mCacheMap.put(key, --cValue);
        }

        if (position > 0) {
            int i = position - 1;
            while (true) {
                Object o = mList.get(i);
                if (o instanceof SeparatorBean) {
                    SeparatorBean sbean = (SeparatorBean) o;
                    boolean ca = (cValue == aValue);
                    if (sbean.isChecked() != ca) {
                        sbean.setChecked(ca);
                        mSeparatorList.add(sbean);
                        if (ca) {
                            boolean allChecked = confirmIsAllChecked();
                            mListener.onAllCheckedChange(allChecked);
                        } else {
                            mListener.onAllCheckedChange(false);
                        }
                        notifyDataSetChanged();
                    }
                    break;
                }
                i--;
            }
        }

    }

    /**
     * 用于检查当前是否有一个类别被全选中 或 未被全选中
     */
    private void countCacheMapValue(SeparatorBean bean, boolean isChecked) {
        String key = bean.getKey();
        if (isChecked) {
            mCacheMap.put(key, mConfirmMap.get(key));
            boolean allChecked = confirmIsAllChecked();
            mListener.onAllCheckedChange(allChecked);
        } else {
            mCacheMap.put(key, 0);
            mListener.onAllCheckedChange(false);
        }
    }

    /**
     * 判断是否全选中
     *
     * @return
     */
    private boolean confirmIsAllChecked() {
        Set<String> keySet = mConfirmMap.keySet();
        for (String key : keySet) {
            int value1 = mCacheMap.get(key);
            int value2 = mConfirmMap.get(key);
            if (value1 != value2) {
                return false;
            }
        }
        return true;
    }

    /**
     * 恢复CacheMap到默认状态
     */
    private void initCacheMap(boolean init) {
        Set<String> keySet = mConfirmMap.keySet();
        for (String key : keySet) {
            if (init) {
                mCacheMap.put(key, 0);
            } else {
                mCacheMap.put(key, mConfirmMap.get(key));
            }
        }
    }

    private void setCheckedVideo(boolean checked) {
        if (checked) {
            mCheckedVideoNum += 1;
        } else {
            mCheckedVideoNum -= 1;
        }
        if ((mCheckedVideoNum == 0 && mHasCheckedVideo)) {
            mHasCheckedVideo = false;
            if (mListener != null) {
                mListener.onVideoCheckedChange(mHasCheckedVideo, mCheckedVideoNum);
            }
        } else if (mCheckedVideoNum > 0 && !mHasCheckedVideo) {
            mHasCheckedVideo = true;
            if (mListener != null) {
                mListener.onVideoCheckedChange(mHasCheckedVideo, mCheckedVideoNum);
            }
        } else if (mCheckedVideoNum >= 0) {
            if (mListener != null) {
                mListener.onVideoCheckedChange(mHasCheckedVideo, mCheckedVideoNum);
            }
        }

        //这个处理防止reset之后才触发的setCheckedVideo发生错误
        if (mCheckedVideoNum < 0) {
            mCheckedVideoNum = 0;
        }
    }

    //重置保存的video的信息并回调
    private void resetCheckedVideo() {
        mCheckedVideoNum = 0;
        if ((mCheckedVideoNum == 0 && mHasCheckedVideo)) {
            mHasCheckedVideo = false;
            if (mListener != null) {
                mListener.onVideoCheckedChange(mHasCheckedVideo, mCheckedVideoNum);
            }
        }
    }

    //初始化用于存储video的变量
    private void initCheckedVideo() {
        mCheckedVideoNum = 0;
        mHasCheckedVideo = false;
    }

    //继承ArrayList用于回调数目
    class MyArrayList<ThumbnailBean> extends ArrayList<ThumbnailBean> {
        @Override
        public boolean remove(Object object) {
            boolean result = super.remove(object);
            if (mListener != null) {
                mListener.onCheckedNumChange(mHasCheckedVideo, size());
            }
            return result;
        }

        @Override
        public boolean add(ThumbnailBean object) {
            boolean result = super.add(object);
            if (mListener != null) {
                mListener.onCheckedNumChange(mHasCheckedVideo, size());
            }
            return result;
        }

        @Override
        public void clear() {
            super.clear();
            if (mListener != null) {
                mListener.onCheckedNumChange(mHasCheckedVideo, size());
            }
        }

        /**
         * @param flag
         */
        public void clear(boolean flag) {
            super.clear();
            if (flag) {
                if (mListener != null) {
                    mListener.onCheckedNumChange(mHasCheckedVideo, size());
                }
            }
        }
    }

    /**
     * 计算索引
     *
     * @param map
     */
    private void countIndexer(HashMap<String, Integer> map) {
        String[] keySet = new String[]{};
        keySet = map.keySet().toArray(keySet);
        int len = keySet.length;
        mPhotoLength = 0;
        mIndexMap = new LinkedHashMap<String, Integer>(len, 1f, false);
        if (len != 0) {
            int index = 0;
            for (int i = 0; i < len; i++) {
                String key = keySet[i];
                int bannerAdCount = 0;
                while (key.contains("sponsored")) {
                    bannerAdCount++;
                    i++;
                    if (i >= len) {
                        break;
                    }
                    key = keySet[i];
                }
                mIndexMap.put(key, index);
                int num = map.get(key);
                if (i < len - 1) {// 加上广告的数量
                    i++;
                    key = keySet[i];
                    num += map.get(key);
                }
                index++;
                index += bannerAdCount;//若有广告插入，加上对应行数
                int count = num / mColNum;
                if (num % mColNum != 0) {
                    count += 1;
                }
                mPhotoLength += count;
                index += count;
            }
        }
//		for(String key: mIndexMap.keySet()){
//			System.out.println("key = " + key + "  value = " + mIndexMap.get(key));
//		}
        String[] str = new String[mIndexMap.size()];
        mIndexkey = mIndexMap.keySet().toArray(str);
    }

    @Override
    public Object[] getSections() {
        return mIndexkey;
    }

    /**
     * 获取当前Selection的第一个position
     */
    @Override
    public int getPositionForSection(int sectionIndex) {
        return mIndexMap.get(mIndexkey[sectionIndex]);
    }

    /**
     * 获取当前Selection的第一个position
     */
    public int getPositionForSectionNoAd(int sectionIndex) {
        return mIndexMap.get(mIndexkey[sectionIndex]);
    }

    /**
     * 获取当前position所属的Selection
     */
    @Override
    public int getSectionForPosition(int position) {
        int len = mIndexkey.length;
        for (int i = 0; i < len; i++) {
            int index = getPositionForSection(i);
            if (position >= index) {
                continue;
            } else {
                return Math.max(0, i - 1);
            }
        }
        return len - 1;
    }

    /**
     * 获取listView所有子View的总长度
     *
     * @return
     */
    public int getListLength() {
        return mIndexkey.length * SEPARATOR_HEIGHT + mPhotoLength * mImageWidth + LAST_BOTTOM_MARGIN;
    }

    /**
     * 获取listView单个的最大高度
     *
     * @return
     */
    public int getSingleHeight() {
        return SEPARATOR_HEIGHT > mImageWidth ? SEPARATOR_HEIGHT : mImageWidth;
    }

    /**
     * 当前position前面所有item的总长度
     *
     * @param position
     * @return
     */
    public int getPositionTopLength(int position) {
        int selection = getSectionForPosition(position);
        int result = 0;
        if (selection >= 0) {
            int index = getPositionForSection(selection);
            if (position == index) {//刚刚是第一个
                result = selection * SEPARATOR_HEIGHT + (position - selection) * mImageWidth;
            } else {
                result = (selection + 1) * SEPARATOR_HEIGHT + (position - selection - 1) * mImageWidth;
            }
        }
        return result;
    }

    public int getPositionFromLength(int length) {
        int len = mIndexkey.length;
        for (int i = 0; i < len; i++) {
            int index = getPositionForSection(i);
            int plength = getPositionTopLength(index);
            if (length < plength) {
                int num = mConfirmMap.get(mIndexkey[i != 0 ? i - 1 : 0]);
                int count = num / mColNum;
                if (num % mColNum != 0) {
                    count += 1;
                }
                count = count * mImageWidth;
                //count是这一组photo的行数
                int size = (plength - length) / mImageWidth + 1;
                if (plength - length > count) {
                    return getPositionForSection(i != 0 ? i - 1 : 0);
                } else {
                    int result = index - size;
                    result = Math.max(0, result);
                    return result;
                }
            } else if (i == len - 1) {//length比最后一组的第一个要大
                int dy = length - plength;
                if (dy > SEPARATOR_HEIGHT) {
                    int result = index + (dy - SEPARATOR_HEIGHT) / mImageWidth + 1;
                    result = Math.min(result, mIndexkey.length + mPhotoLength - 1);
                    return result;
                } else {
                    return index;
                }
            }
        }
        return mIndexkey.length + mPhotoLength - 1;
    }

    /**
     * 用于ArrayAdapter中getView的缓存
     */
    private class ViewHolder {
        GalleryRowItem item;
    }
}